<?php

namespace app\Admin\controller;

use think\Controller;
use think\Request;
use app\common\model\ActivityCategory as cateModel;

class ActivityCategory extends Controller
{
    protected $middleware = ['adminauth'];
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $datas = cateModel::order('sorder')->all();
        return view('activity_category/index', ['datas' => $datas]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('activity_category/create');
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $valiResult = $this->validate($request->post(), 'app\admin\validate\activitycate');
        if(true !== $valiResult)
        {
            $this->error($valiResult);
        }
        $datas = $request->post();
        if($request->has('picture', 'file'))
        {
            $file = $request->file('picture');
            $info = $file->validate(['size'=>200000,'ext'=>'jpg,png,jpeg'])->move('./static/icons');
            if(!$info)
            {
                $this->error($file->getError());
            }
            $datas['icon'] = $info->getSaveName();
        }
        cateModel::create($datas);
        $this->success('添加成功', 'ActivityCategory/index',1);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $data = cateModel::getOrFail($id);
        return view('activity_category/create', ['data' => $data]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $row = cateModel::getOrFail($id);
        $valiResult = $this->validate($request->post(), 'app\admin\validate\activitycate');
        if(true !== $valiResult)
        {
            $this->error($valiResult);
        }

        $datas = $request->post();
        if($request->has('picture', 'file'))
        {
            $file = $request->file('picture');
            $info = $file->validate(['size'=>200000,'ext'=>'jpg,png,jpeg'])->move('./static/icons');
            if(!$info)
            {
                $this->error($file->getError());
            }
            $datas['icon'] = $info->getSaveName();
        }
        $row->save($datas);
        $this->success('修改成功', 'ActivityCategory/index');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        cateModel::destroy($id);
        return json(['status' => 1]);
    }
}
